/**
 * 仅针对请求成功时，不同状态码对应的不同逻辑
 */
import store from '@/store'
import ErrorCode from '../errorCode'
import { MessageBox, Message } from 'element-ui'

const SuccessHandler = function(response) {
  const code = Number(response.data.code) || 200
  const msg = response.data.msg || ErrorCode[response.data.code]

  if (code === 401) {
    MessageBox.confirm(msg, '系统提示', {
      confirmButtonText: '重新登录',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      store.dispatch('LogOut').then(() => {
        window.location.href = '/'
      })
    })
  }

  if (code === 500) {
    Message({
      message: msg,
      type: 'error'
    })
    return Promise.reject(new Error(msg))
  }
  // if (code !== 200) {
  //   Message({
  //     message: msg,
  //     type: 'error'
  //   })
  //   return Promise.reject(new Error('error'))
  // }

  // 导出时需要响应头中的信息
  const headers = response.headers
  if (headers['content-type'] === 'application/octet-stream;charset=utf-8') {
    return { headers, data: response.data }
  }
  return Promise.resolve(response.data)
}

export default SuccessHandler
